let listLoad = require('../../common/mixinList')
import { formatTime } from '../../utils/util'
Page({
    behaviors: [listLoad],
    data: {
        navInfo: '',
        usePrivateMethod: true,
        rounds: '一', //当前场次
        time: 0, //当前场次交易结束倒计时时间
        timeData: {}, //倒计时格式化后的时间
        nextTimeLabel: '', //下场开始时间
        classList: [], //分类列表
        classFirstActive: 1, //左侧选中分类索引
        colorList: [], //颜色选项列表
        salesRanking: false, //true时按照销量最高排序
        scrollTop: 0,
        screenPopupShow: false, //展示筛选弹出层
        screenPopupTop: 0, //筛选弹出层的top位置
        screenPopupMaxHeight: 0, //筛选弹出层的最大高度
        colorCardIndex: null, //备选色卡的索引
        colorCardConfirmIndex: null, //生效的色卡的索引
        isCollect: false, //点击关注品类，触发重新登录时不重新请求

    },
    timeOutId: '', //定时任务定时器，页面销毁时清除
    onLoad: function(options) {
        this.setData({
            navInfo: getApp().globalData.navInfo
        })
        if (options.uid) { //页面分享携带uid绑定关系
            return this.redirect_login(options.uid)
        }

        options.isCollect === 'true' && this.setData({ classFirstActive: 0 })
        options.searchText && this.setData({ searchText: options.searchText })

        if (this.data.isCollect) {
            this.setData({ classFirstActive: 0 })
            return this.getList(true)
        }
        this.getBusiness()
        this.getClassList(options.id)
        this.getColorList()
        this.timedTask({ //参数的说明
            interval: 1, //间隔天数，间隔为整数
            runNow: false, //是否立即运行
            time: "00:00:00" //执行的时间点 时在0~23之间
        }, this.getBusiness)
    },
    getReqUrl() { //增加一个方法改变url请求参数,需要时在页面内覆盖此方法(this.data.reqUrl不存在时生效)
        return this.data.classFirstActive === 0 ? '/api/user/collect/index?type=1' : '/api/product/items'
    },
    getParamsData() { //页面特殊的请求参数，需要时在页面内覆盖此方法，默认返回{}
        const { classList, classFirstActive, colorList, colorCardConfirmIndex, searchText, salesRanking } = this.data
        if (classFirstActive === 0) {
            this.data.isCollect = true
            return { limit: 20 }
        }
        let params = { cate_id: classList[classFirstActive].cate_id, limit: 15 }
        if (colorCardConfirmIndex != null) params.color_id = colorList[colorCardConfirmIndex].color_id
        if (salesRanking) params.order = 'sales'
        if (searchText) params.so = searchText
        return params
    },
    //获取分类
    getClassList(id) {
        this.request({
            url: '/api/product/cate',
            login: false,
        }, res => {
            res.data.unshift({
                title: '我的收藏'
            })
            this.setData({ classList: res.data })
            if (id) { //匹配索引
                const findIndex = res.data.findIndex(item => {
                    return item.cate_id === Number(id)
                })
                if (findIndex > -1) this.setData({ classFirstActive: findIndex })
            }
            this.getList(true)
        })
    },
    //获取颜色选项
    getColorList() {
        this.request({
            url: '/api/product/color',
            login: false
        }, res => {
            this.setData({
                colorList: res.data
            })
        })
    },
    onReady: function() {
        //获取筛选栏位置信息
        this.getRect(".screen").then(res => {
            let screenPopupMaxHeight = wx.getSystemInfoSync().windowHeight - res.bottom
            this.setData({ screenPopupTop: res.bottom, screenPopupMaxHeight })
        })
    },
    /**获取交易时间段 */
    getBusiness() {
        this.request({
            url: '/api/index/config?type=2',
            login: false
        }, res => {
            const orderPeriod = res.data
            const today = formatTime(new Date()).slice(0, 10).replaceAll('-', '/')
            const endTime = new Date(today + ' ' + orderPeriod.trade_ltime).getTime()
            let remainingTime = endTime - Date.now() //单天第一场结束时间戳

            //获取下场开始时间戳
            const nextTime = endTime + orderPeriod.stop_trade * 60 * 1000
            //格式化下场开始交易时间
            const nextTimeLabel = formatTime(new Date(nextTime)).slice(11, 16)

            /**大于0-->单天第一次交易时间段 */
            if (remainingTime > 0) {
                this.setData({ time: remainingTime, nextTimeLabel, rounds: '一' })
            } else {
                /**判断是否处于禁止交易时间段，处于显示第一场倒计时0，不处于则为第二场，计算单日23:59:59的倒计时，提示设置下场交易时间为0:0 */
                if (Date.now() < nextTime) { //禁止交易时间段
                    this.setData({ time: 0.1, nextTimeLabel })
                    //新建定时任务，禁止交易时间段结束后，重新你请求接口
                    this.timedTask({ //参数的说明
                        interval: 1, //间隔天数，间隔为整数
                        runNow: false, //是否立即运行
                        time: nextTimeLabel + ':00' //执行的时间点
                    }, this.getBusiness)
                } else {
                    //计算23:59:59离现在的时间戳
                    const secondEndTime = new Date(today + ' 23:59:59').getTime()
                    let secondRemainingTime = secondEndTime + 1000 - Date.now() //单天第二场结束时间戳
                    this.setData({ time: secondRemainingTime, nextTimeLabel: '0:00', rounds: '二' })
                }
            }
        })
    },
    /**定时任务，页面开启状态每天凌晨0:00执行 */
    timedTask(config, func) {
        config.runNow && func()
        const nowTime = new Date().getTime()
        const timePoints = config.time.split(':').map(i => parseInt(i))
        let recent = new Date().setHours(...timePoints)
        recent >= nowTime || (recent += 24 * 3600000)
        this.timeOutId = setTimeout(() => {
            func()
            clearTimeout(this.timeOutId)
            setInterval(func, config.interval * 3600000)
        }, recent - nowTime)
    },
    onCountDownChange({ detail }) {
        detail.days = detail.days.toString().padStart(2, '0')
        detail.hours = detail.hours.toString().padStart(2, '0')
        detail.minutes = detail.minutes.toString().padStart(2, '0')
        detail.seconds = detail.seconds.toString().padStart(2, '0')
        this.setData({ timeData: detail })
    },
    privateMethod(refresh, res) { //页面使用此Behavior私有方法,需要时在页面内覆盖此方法
        return new Promise(resolve => {
            if (this.data.classFirstActive === 0) {
                let result = res.data.filter(item => {
                    return !Array.isArray(item.collect_info)
                })
                resolve(result.map(item => {
                    return { ...item.collect_info, collected: 1 }
                }))
                return
            }
            resolve(res.data)
        })
    },
    //切换分类
    onSideBarChange({ detail }) {
        if (this.data.classFirstActive === detail || this.data.screenPopupShow) return
        this.setData({ classFirstActive: detail, scrollTop: 0, list: [], searchText: '' })
        this.getList(true)
    },
    //点击销量排序
    setSalesRangk() {
        this.setData({ salesRanking: !this.data.salesRanking, list: [], screenPopupShow: false })
        this.getList(true)
    },
    //前往商品列表页
    toGoodsList({ mark }) {
        const { index, collect } = mark
        if (index == undefined) return
        let info = this.data.list[index]
        if (collect) { //关注
            return this.request({
                url: '/api/user/collect/collect',
                method: 'POST',
                data: {
                    status: info.collected ? 0 : 1,
                    can_id: info.product_common_id,
                    type: '1'
                }
            }, () => {
                wx.showToast({
                    title: info.collected ? '取消成功' : '收藏成功',
                    icon: 'success'
                })
                this.setData({
                    ['list[' + index + '].collected']: info.collected ? 0 : 1
                })
            })
        }
        wx.navigateTo({
            url: `/pages/hall_goods/index?cate_id=${this.data.list[index].cate_id}&color_id=${this.data.list[index].color_id}&product_common_id=${this.data.list[index].product_common_id}`
        })
    },
    //点击颜色筛选
    setScreenPopupShow() {
        this.setData({ screenPopupShow: !this.data.screenPopupShow })
    },
    //点击色卡
    chooseColor({ mark }) {
        if (mark.index == undefined) return
        this.setData({ colorCardIndex: mark.index })
    },
    //重置色卡
    resetColorCard() {
        this.setData({ colorCardIndex: null })
    },
    //确认选择色卡
    confirmColorCard() {
        this.setData({ colorCardConfirmIndex: this.data.colorCardIndex, screenPopupShow: false, list: [] })
        this.getList(true)
    },
    //关闭颜色筛选弹出层
    hideScreenPopup() {
        console.log('jkjk');
        this.setData({ screenPopupShow: false, colorCardIndex: this.data.colorCardConfirmIndex })
    },
    //获取节点位置信息
    getRect(selector) {
        return new Promise(function(resolve) {
            wx.createSelectorQuery()
                .select(selector)
                .boundingClientRect()
                .exec(function(rect) {
                    if (rect === void 0) {
                        rect = [];
                    }
                    return resolve(rect[0]);
                })
        })
    },
    refresh() {
        // if (this.data.classList.length > 0) {
        //     //重置颜色。重新请求
        //     this.setData({
        //         colorCardIndex: null, //备选色卡的索引
        //         colorCardConfirmIndex: null
        //     })
        //     this.getList(true)
        // }
        this.getBusiness()
        this.timedTask({ //参数的说明
            interval: 1, //间隔天数，间隔为整数
            runNow: false, //是否立即运行
            time: "00:00:00" //执行的时间点 时在0~23之间
        }, this.getBusiness)
    },
    //点击分享
    onShareAppMessage() {
        const { classList, classFirstActive, userInfo, searchText } = this.data
        let options = `/pages/trading_hall/index?id=${classList[classFirstActive].cate_id}&isCollect=${classFirstActive===0}`
        if (searchText) options += `&searchText=${searchText}`
        if (userInfo) options += `&uid=${userInfo.uid}`
        return {
            path: options
        }
    },
    onHide: function() {
        this.setData({ searchText: '' })
    },
    onUnload() {
        clearTimeout(this.timeOutId)
    }
})